package com.fjnu.controller.shiro;

import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fjnu.controller.common.BaseController;
import com.fjnu.entities.Role;
import com.fjnu.entities.User;
import com.fjnu.service.IRoleService;
import com.fjnu.service.IUserService;

/**
 * 用户与角色之间的相关操作
 * @author 默默
 *
 */
@Controller
public class UserRoleController extends BaseController{
	private static Logger logger =LogManager.getLogger(UserRoleController.class);
	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	@RequestMapping("/addRoleToUser")
	@ResponseBody
	public Map<String,Object> addRoleToUser(int userId,int roleId){
		logger.info("给用户分配角色");
		if(!init(userId,roleId).get(STATUS).equals(SUCCESS))
			return getData2Result();
	    User user = userService.findUserUnique(userId);
		Role role = roleService.findRoleUnique(roleId);
		//roleService.addRole(role);
		role.getUserList().add(user);
		user.getRoleList().add(role);
		roleService.addRole(role);
		userService.updateUser(user);
		return getData2Result();
	}
	@RequestMapping("/delRoleToUser")
	@ResponseBody
	public Map<String,Object> delRoleToUser(int userId,int roleId){
		logger.info("删除某个用户的角色");
		if(!init(userId,roleId).get(STATUS).equals(SUCCESS))
			return getData2Result();
		User user = userService.findUserUnique(userId);
		Role role = roleService.findRoleUnique(roleId);
		role.getUserList().remove(user);
		user.getRoleList().remove(role);
		roleService.addRole(role);
		userService.updateUser(user);
		return getData2Result();
		}
 }
